﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Abmemunit.Data.Infrastructure;
using Abmemunit.Domain.Fakes;
using Abmemunit.Services.Security;
using Abmemunit.Services.Users;
using NUnit.Framework;
using Abmemunit.Domain.Users;
using Rhino.Mocks;
using Assert = NUnit.Framework.Assert;

namespace Abmemunit.Services.Tests.Users
{
    [TestFixture]
    public class UserServiceTest
    {
        IRepository<User> _userRepo;
        IRepository<UserRole> _userRoleRepo;
        private IUserService _userService;
        private IEncryptionService _encryptionService;
        private HttpContextBase _httpContext;

        [SetUp]
        public void SetUp()
        {
            _httpContext = new FakeHttpContext("localhost");
            _userRepo = MockRepository.GenerateMock<IRepository<User>>();
            _userRoleRepo = MockRepository.GenerateMock<IRepository<UserRole>>();
            _encryptionService = new EncryptionService();


            var adminRole = new UserRole()
            {
                Name = UserRoleNames.Administrators,
                Active = true
            };

            var memberRole = new UserRole()
            {
                Name = UserRoleNames.Members,
                Active = true
            };

            var user1 = new User()
                            {
                                Username = "test",
                                Email = "test@test.com",
                                Password = "password",
                                Active = true,
                                IsAdminAccount = true,
                                CreatedOnUtc = DateTime.UtcNow
                            };

            user1.UserRoles.Add(adminRole);

            string saltKey = _encryptionService.CreateSaltKey(5);
            string password = _encryptionService.CreatePasswordHash("password", saltKey);
            user1.PasswordSalt = saltKey;
            user1.Password = password;

            _userRoleRepo.Expect(x => x.Table).Return(new List<UserRole>() { adminRole, memberRole }.AsQueryable());
            _userRepo.Expect(x => x.Table).Return(new List<User>() { user1 }.AsQueryable());
            _userService = new UserService(_userRepo, _userRoleRepo,  _encryptionService, _httpContext);


        }


        [Test]
        public void Can_load_user_by_name()
        {
            var usr10 = _userService.GetUserByName("test");
            Assert.IsNotNull(usr10);

        }

        [Test]
        public void Can_validate_an_user()
        {
            var user = new User() { Username = "test", Password = "password" };
            bool result = _userService.ValidateUser(user);
            Assert.IsTrue(result);
        }
    }
}
